import CryptoJS from "crypto-js";

/**
 * 随机生成字符串
 * @param len 指定生成字符串长度
 */
export function getRandomString(len) {
  let _charStr =
      "abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789",
    min = 0,
    max = _charStr.length - 1,
    _str = ""; //定义随机字符串 变量
  //判断是否指定长度，否则默认长度为15
  len = len || 15;
  //循环生成字符串
  for (var i = 0, index; i < len; i++) {
    index = (function (randomIndexFunc, i) {
      return randomIndexFunc(min, max, i, randomIndexFunc);
    })(function (min, max, i, _self) {
      let indexTemp = Math.floor(Math.random() * (max - min + 1) + min),
        numStart = _charStr.length - 10;
      if (i == 0 && indexTemp >= numStart) {
        indexTemp = _self(min, max, i, _self);
      }
      return indexTemp;
    }, i);
    _str += _charStr[index];
  }
  return _str;
}

/**
 * 加密
 * @param data 请求的body
 */

export const AES_Encrypt = (timestamp, nonce, data) => {
  let kv = "";
  Object.keys(data)
    .sort()
    .forEach((item, index) => {
      kv += item + data[item];
    });
  let signature = timestamp + nonce + kv;
  let hash = CryptoJS.HmacSHA256(signature, "diankai_123_aux");
  let hashInHex = CryptoJS.enc.Hex.stringify(hash);
  return hashInHex;
};
